package com.example.yichuangyun.mvvm.ui.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.FragmentCustomInfoBinding;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.company.CompanyDataModel;
import com.example.yichuangyun.model.company.CustomInfoDataModel;
import com.example.yichuangyun.mvvm.base.BaseFragment;
import com.example.yichuangyun.mvvm.ui.activity.ImproveCompanyInfoActivity;
import com.example.yichuangyun.mvvm.ui.adapter.CustomInfoAdapter;
import com.example.yichuangyun.mvvm.ui.fragment.view.CustomInfoViewModel;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.UiUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自主信息
 */
public class CustomInfoFragment extends BaseFragment<FragmentCustomInfoBinding, CustomInfoViewModel> {

    private CompanyDataModel.CompanyModel companyModel;
    private List<CustomInfoDataModel.CustomInfoModel> data = new ArrayList<>();
    private CustomInfoAdapter adapter;
    private int page = 1;
    private String eid;

    @Override
    protected CustomInfoViewModel bindModel() {
        return getViewModel(this, CustomInfoViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        if (getArguments() != null) {
            companyModel = (CompanyDataModel.CompanyModel) getArguments().getSerializable(Constant.modelKey);
            binding.setCompanyModel(companyModel);
            eid = companyModel.getEid();
            Glide.with(mContext).load(companyModel.getLogoUrl()).placeholder(R.mipmap.icon_company_def_logo).into(binding.includeTopDetails.ivCompanyLogo);
            final List<String> tags = new ArrayList<>();
            if (!TextUtils.isEmpty(companyModel.getNewStatusCode())) {
                tags.add(UiUtils.getManagementStatus(companyModel.getNewStatusCode()));
            }
            if (companyModel.isWskh()) {
                tags.add(getString(R.string.wskh));
            }
            if (companyModel.getPayTaxeState() == 1) {
                tags.add(getString(R.string.a_nsr));
            }
            if (companyModel.getTelCount() > 0) {
                tags.add(getString(R.string.tel_count, companyModel.getTelCount()));
            }
            binding.includeTopDetails.tagCloudView.setTags(tags);

            if (companyModel.getIndustryCodeList() != null && companyModel.getIndustryCodeList().size() > 0) {
                StringBuilder industryBuilder = new StringBuilder();
                for (String s : companyModel.getIndustryCodeList()) {
                    industryBuilder.append(s).append(",");
                }
                binding.includeTopDetails.tvIndustry.setText(Html.fromHtml(mContext.getString(R.string.industry, industryBuilder.substring(0, industryBuilder.toString().length() - 1)), Html.FROM_HTML_MODE_LEGACY));
            } else {
                binding.includeTopDetails.tvIndustry.setText(Html.fromHtml(mContext.getString(R.string.industry, "--"), Html.FROM_HTML_MODE_LEGACY));
            }

            binding.includeTopDetails.tvCompanyAddress.setText(Html.fromHtml(mContext.getString(R.string.company_address, CommonUtil.setText3(companyModel.getAddress())), Html.FROM_HTML_MODE_LEGACY));
            binding.includeTopDetails.tvReportAddress.setText(Html.fromHtml(mContext.getString(R.string.company_address_report, CommonUtil.setText3(companyModel.getReportAddress())), Html.FROM_HTML_MODE_LEGACY));

            if (companyModel.getWebUrls() != null && companyModel.getWebUrls().size() > 0) {
                StringBuilder webSiteBuilder = new StringBuilder();
                for (String s : companyModel.getWebUrls()) {
                    webSiteBuilder.append(s).append(",");
                }
                binding.includeTopDetails.tvCompanyWebsite.setText(Html.fromHtml(mContext.getString(R.string.company_website, webSiteBuilder.substring(0, webSiteBuilder.toString().length() - 1)), Html.FROM_HTML_MODE_LEGACY));
            } else {
                binding.includeTopDetails.tvCompanyWebsite.setText(Html.fromHtml(mContext.getString(R.string.company_website, "--"), Html.FROM_HTML_MODE_LEGACY));
            }
        }

        adapter = new CustomInfoAdapter(mContext, data);
        binding.recyclerView.setAdapter(adapter);
    }

    @Override
    protected void lazyLoadData() {
        getCustomList(page);
    }

    @Override
    protected void initClick() {
        viewModel.onDelayClick(binding.cvImproveInfo, o -> {
            Bundle bundle = new Bundle();
            bundle.putString(Constant.eidKey, companyModel.getEid());
            bundle.putString(Constant.creditNoKey, companyModel.getCreditNo());
            JumpIntent.jump((Activity) mContext, ImproveCompanyInfoActivity.class, bundle);
        });

        // 自主信息列表返回结果
        viewModel.customInfoDataModelMutableLiveData.observe(this, customInfoDataModel -> {
            List<CustomInfoDataModel.CustomInfoModel> list = customInfoDataModel.getRecords();
            if (list.size() < Constant.pageSize) {
                binding.smartRefreshLayout.finishLoadMoreWithNoMoreData();
            }
            if (page == 1) {
                data = list;
                adapter.onRefresh(list);
                binding.smartRefreshLayout.finishRefresh();
            } else {
                adapter.addData(list);
                binding.smartRefreshLayout.finishLoadMore();
            }
        });

        // 列表返回结果错误
        viewModel.errorMutableLiveData.observe(this, s -> {
            binding.smartRefreshLayout.finishRefresh();
            binding.smartRefreshLayout.finishLoadMore();
        });

        binding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getCustomList(page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getCustomList(page);
            }
        });

        binding.includeTopDetails.tvCompanyAddress.setOnLongClickListener(view -> {
            if (!TextUtils.isEmpty(companyModel.getAddress())) {
                CommonUtil.copyText(mContext, companyModel.getAddress());
            }
            return false;
        });
        binding.includeTopDetails.tvReportAddress.setOnLongClickListener(view -> {
            if (!TextUtils.isEmpty(companyModel.getReportAddress())) {
                CommonUtil.copyText(mContext, companyModel.getReportAddress());
            }
            return false;
        });
    }

    /**
     * 获取自主信息列表
     */
    private void getCustomList(int page) {
        Map<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("eid", eid);
        viewModel.getCustomList(map);
    }

    public static CustomInfoFragment newInstance(CompanyDataModel.CompanyModel companyModel) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constant.modelKey, companyModel);
        CustomInfoFragment fragment = new CustomInfoFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (eventBusModel.getMsg().equals(Constant.refreshCustomList)) {
                page = 1;
                getCustomList(page);
            }
        }
    }
}
